package com.solarStruggle.graphics

import java.awt.{Color}
import java.awt.image.{BufferedImage => JBufferedImage}
import java.io.{Serializable}

@serializable
class BufferedImage(width: Int, height: Int)
extends JBufferedImage(width, height, JBufferedImage.TYPE_4BYTE_ABGR) {
  
  /**
   * Converts a color to an int array
   */
  implicit def colorToIntArray(c: Color): Array[Int] =
    Array(c.getRed, c.getGreen, c.getBlue, c.getAlpha)

  /**
   * Clears the image with black pixels
   */
  def clear(fill: Color) {
    val g = getGraphics
    g.setColor(fill)
    g.fillRect(0, 0, width, height)
  }

  /**
   * Returns the color at a given point in the buffer
   */
  def getPixel(x: Int, y: Int): Color = {
    if(x < 0 || y < 0 || x >= getWidth || y >= getHeight) {
      Color.BLACK
    } else {
      val data = getRGB(x, y)
      new Color((data >>> 16) & 0xFF,
                (data >>>  8) & 0xFF,
                (data >>>  0) & 0xFF,
                (data >>> 24) & 0xFF)
    }
  }
  
  /**
   * Sets a pixel at the given location to the given color
   */
  def setPixel(x: Int, y: Int, color: Color) {
    if(x >= 0 && y >= 0 && x < getWidth && y < getHeight) {
      setRGB(x, y,
             (color.getAlpha << 24) | 
             (color.getRed   << 16) | 
             (color.getGreen << 8) | 
             (color.getBlue  << 0))
    }
  }
}
